package com.apes.scm.masterdata.stock.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.model.PartySerialNumber;
import com.apes.scm.masterdata.party.repository.PartySerialNumberRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 功能：逻辑仓库
 *
 * @author xul
 * @create 2018-01-26 15:25
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Depot.CONST_TABLE_NAME)
public class Depot extends Model {
    public static final String CONST_TABLE_NAME = "mas_depot";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = "mas_depot_sequence", name = "仓库", prefix = "%(company)", padding = 3)
    @Comment("编码")
    private String id;

    @Column(name = "name", length = 120, nullable = false)
    @Comment("仓库名称")
    private String name; //仓库名称

    @Column(name = "display_name", length = 120)
    @Comment("显示名称")
    private String displayName; //显示名称

    @NotNull
    @ManyToOne
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company; //公司

    @Column(name = "ORIGIN", length = 20)
    @Comment("外部ID")
    private String origin; //外部ID

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("有效标记")
    private boolean valid = true; //有效
//
//    @OneToMany(mappedBy="depot")
//    private Set<Location> locations = new HashSet(); //库区


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("所属部门")
    private Dept dept; //所属部门


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "depot_level", referencedColumnName = "id")
    @Comment("仓库级别编码")
    private Enumeration depotLevel;  //仓库级别（0:门店；1：区域中心仓；2：配送中心）


    public String obtainDepotId(Depot depot) {
        //获取逻辑仓库编码
        List<PartySerialNumber> serialNumbers = SpringManager.getBean(PartySerialNumberRepository.class).findAll(
                JpaDsl.toCriteriaByEq(
                        "companyId", depot.getCompany().getId()
                ));
        if (serialNumbers.size() <= 0) {
            throw new RuntimeException(String.format("公司[%s][%s]不存在于公司维度自增编码流水号记录表，无法生产新的部门编码，请检查公司是否存在！", depot.getCompany().getId(), depot.getCompany().getName()));
        }
        String byMaxDepotId = SpringManager.getBean(PartySerialNumberRepository.class).findByMaxDepotId(Integer.parseInt(depot.getCompany().getId()));
        int depotId = Integer.parseInt(byMaxDepotId);
        //逻辑仓库编码+1后保存
        serialNumbers.get(0).setDepotId(depotId + 1);
        PartySerialNumber partySerialNumber = SpringManager.getBean(PartySerialNumberRepository.class).saveAndFlush(serialNumbers.get(0));
        return depot.getCompany().getId() + String.format("%3d", partySerialNumber.getDepotId()).replace(" ", "0");
    }
}
